package com.lc.zpyh.ui.activity.home;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.base.BaseDialog;
import com.lc.zpyh.R;
import com.lc.zpyh.app.AppActivity;
import com.lc.zpyh.bean.StockEntity;
import com.lc.zpyh.http.request.ReturnhotWordsApi;
import com.lc.zpyh.http.request.SelectCanteenAndSupermarketBySchoolIdApi;
import com.lc.zpyh.http.response.ReturnhotWordsBean;
import com.lc.zpyh.http.response.SelectCanteenAndSupermarketBySchoolIdBean;
import com.lc.zpyh.other.IntentKey;
import com.lc.zpyh.sqlite.RecordsDao;
import com.lc.zpyh.ui.dialog.MessageDialog;
import com.lc.zpyh.util.SPUtil;
import com.lc.zpyh.view.JiGuiPopupWindow;
import com.lc.zpyh.view.ShiTangPopupWindow;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SearchActivity extends AppActivity {
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.rl_search)
    RelativeLayout rlSearch;
    @BindView(R.id.rl_clear)
    RelativeLayout rlClear;
    @BindView(R.id.title_bar_txt_right)
    TextView titleBarTxtRight;
    @BindView(R.id.rl_layout_focus)
    RelativeLayout rlLayoutFocus;
    @BindView(R.id.rv_popular_searches)
    RecyclerView rvPopularSearches;
    @BindView(R.id.rv_searchRecords)
    RecyclerView rvSearchRecords;
    @BindView(R.id.ll_searchRecords)
    LinearLayout llSearchRecords;
    @BindView(R.id.tv_1)
    TextView tv1;

    List<String> dataBeanList=new ArrayList<>();
    List<String> dataPopularBeanList=new ArrayList<>();

    private BaseQuickAdapter<StockEntity, BaseViewHolder> seachHistoryAdapter;
    private BaseQuickAdapter<String, BaseViewHolder> popularadapter;

    private List<StockEntity> searchRecordsList;
    private List<StockEntity> tempList;
    private RecordsDao recordsDao;
    private static final String TAG = "SearchActivity";
    private ShiTangPopupWindow shiTangPopupWindow;
    private String canteenid="0";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        setShitang();
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(!TextUtils.isEmpty(etSearch.getText().toString().trim())){
                    rlSearch.setVisibility(View.VISIBLE);
                }
            }
        });

//热门
        searchPopular();
        /**
         *   历史记录数据
         */

        recordsDao = new RecordsDao(this);
        searchRecordsList = new ArrayList<>();
        tempList = new ArrayList<>();
        tempList.addAll(recordsDao.findAll());
        Log.e(TAG, "initData: "+tempList.size() );
        reversedList();
        //第一次进入判断数据库中是否有历史记录，没有则不显示
        checkRecordsSize();
//         历史记录
        searchrecords();
    }

    @Override
    protected void onStart() {
        super.onStart();

    }
    private void setShitang() {
        EasyHttp.post(this)
                .api(new SelectCanteenAndSupermarketBySchoolIdApi().setSchoolid(SPUtil.get(this, IntentKey.ADDRESSID, ""))).request(new HttpCallback<SelectCanteenAndSupermarketBySchoolIdBean>(this) {

            @Override
            public void onSucceed(SelectCanteenAndSupermarketBySchoolIdBean data) {
//s
                if (data.getCode() == 0) {
                    shiTangPopupWindow = new ShiTangPopupWindow(getContext(), data.getList());

                    shiTangPopupWindow.setOnItemLickenter(new JiGuiPopupWindow.OnItemLickenter() {
                        @Override
                        public void onTypeClick(String type, String id) {
                            canteenid = id;
                            tv1.setText(type);
//                            UpdateAddress();
                        }
                    });
                }


            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }
    private void searchrecords() {

        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(getContext());
        layoutManager.setFlexDirection(FlexDirection.ROW);
        layoutManager.setJustifyContent(JustifyContent.FLEX_START);
        rvSearchRecords.setLayoutManager(layoutManager);
        if (seachHistoryAdapter==null) {
            seachHistoryAdapter = new BaseQuickAdapter<StockEntity, BaseViewHolder>
                    (R.layout.item_home_search, searchRecordsList) {

                @Override
                protected void convert(BaseViewHolder baseViewHolder, StockEntity dataBean) {
                    baseViewHolder.setText(R.id.tv_search_records, dataBean.getName());
                }


            };
            rvSearchRecords.setAdapter(seachHistoryAdapter);
        }else {
            seachHistoryAdapter.notifyDataSetChanged();
        }
        seachHistoryAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                startActivity(new Intent(SearchActivity.this,SearchGoodsActivity.class).putExtra("goodsname",searchRecordsList.get(position).getName()));



            }
        });

    }
    private void searchPopular() {

        EasyHttp.post(this)
                .api(new ReturnhotWordsApi().setNum("").setSchoolId(SPUtil.get(SearchActivity.this,IntentKey.ADDRESSID,""))).request(new HttpCallback<ReturnhotWordsBean>(this) {

            @Override
            public void onSucceed(ReturnhotWordsBean data) {
//
                dataPopularBeanList.clear();
                dataPopularBeanList.addAll(data.getList());
                FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(getContext());
                layoutManager.setFlexDirection(FlexDirection.ROW);
                layoutManager.setJustifyContent(JustifyContent.FLEX_START);
                rvPopularSearches.setLayoutManager(layoutManager);
                popularadapter = new BaseQuickAdapter<String, BaseViewHolder>
                        (R.layout.item_home_search,dataPopularBeanList) {

                    @Override
                    protected void convert(BaseViewHolder baseViewHolder,String dataBean) {
                        baseViewHolder.setText(R.id.tv_search_records,dataBean);
                    }


                };
               popularadapter.setOnItemClickListener(new OnItemClickListener() {
                   @Override
                   public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {

                       if (!recordsDao.isHasRecord(dataPopularBeanList.get(position))) {
                           //将搜索记录保存至数据库中
                           recordsDao.add(dataPopularBeanList.get(position),"");
                       }
                       tempList.clear();

                       tempList.addAll(recordsDao.findAll());
                       reversedList();
                       checkRecordsSize();
                       seachHistoryAdapter.notifyDataSetChanged();
                       startActivity(new Intent(SearchActivity.this,SearchGoodsActivity.class).putExtra("goodsname",dataPopularBeanList.get(position)));
                   }
               });
                rvPopularSearches.setAdapter(popularadapter);
            }
            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });

    }

    //当没有匹配的搜索数据的时候不显示历史记录栏
    private void checkRecordsSize() {
        if (searchRecordsList.size() == 0) {
            llSearchRecords.setVisibility(View.GONE);
        } else {
            llSearchRecords.setVisibility(View.VISIBLE);
        }
    }


    //颠倒list顺序，用户输入的信息会从上依次往下显示
    private void reversedList() {
        searchRecordsList.clear();
        for (int i = tempList.size() - 1; i >= 0; i--) {
            searchRecordsList.add(tempList.get(i));
        }
    }
    @OnClick({R.id.image_back, R.id.rl_clear, R.id.rl_search, R.id.title_bar_txt_right, R.id.tv_searchRecords,R.id.tv_1})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.tv_1:
                if (shiTangPopupWindow.isShowing()) {
                    shiTangPopupWindow.dismiss();
                } else {
                    if (shiTangPopupWindow != null) {
                        WindowManager.LayoutParams lp = getWindow().getAttributes();
                        lp.alpha = 0.7f;
                        getWindow().setAttributes(lp);
                        shiTangPopupWindow.showAsDropDown(rlLayoutFocus,50,0);
                    }
                }
                break;
            case R.id.rl_clear:
                etSearch.setText("");
                rlClear.setVisibility(View.GONE);
                break;

            case R.id.title_bar_txt_right:
//                搜索
                  if (etSearch.getText().toString().isEmpty()){
                      toast("请输入关键字");
                      return;
                  }
                if (!recordsDao.isHasRecord(etSearch.getText().toString().trim())) {
                    //将搜索记录保存至数据库中
                    recordsDao.add(etSearch.getText().toString().trim(),"");
                }
                tempList.clear();

                tempList.addAll(recordsDao.findAll());
                reversedList();
                checkRecordsSize();
                seachHistoryAdapter.notifyDataSetChanged();
                startActivity(new Intent(SearchActivity.this,SearchGoodsActivity.class).putExtra("goodsname",etSearch.getText().toString().trim()).putExtra("id",canteenid));
                break;
            case R.id.tv_searchRecords:
//                删除历史记录
                new MessageDialog.Builder(getActivity())
                        // 标题可以不用填写
                        .setTitle("提示")
                        // 内容必须要填写
                        .setMessage("是否清空全部历史搜索记录")
                        // 确定按钮文本
                        .setConfirm(getString(R.string.common_confirm))
                        // 设置 null 表示不显示取消按钮
                        .setCancel(getString(R.string.common_cancel))
                        // 设置点击按钮后不关闭对话框
                        //.setAutoDismiss(false)
                        .setListener(new MessageDialog.OnListener() {

                            @Override
                            public void onConfirm(BaseDialog dialog) {
                                tempList.clear();
                                reversedList();
                                recordsDao.deleteAllRecords();
                                seachHistoryAdapter.notifyDataSetChanged();
                                llSearchRecords.setVisibility(View.GONE);
                            }

                            @Override
                            public void onCancel(BaseDialog dialog) {
                         dialog.dismiss();
                            }
                        })
                        .show();

                break;
        }
    }
}
